

package com.ims.common.service.login;


import java.sql.Timestamp;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import com.ims.common.dao.login.LoginDao;
import com.ims.common.service.BaseServiceImpl;
import com.ims.stocks.model.Employee;
import com.ims.stocks.model.Role;
import com.ims.stocks.model.UserDetails;
import com.ims.stocks.model.UserLog;


public class LoginServiceImpl extends BaseServiceImpl implements LoginService {

    private static final Logger LOG = Logger.getLogger(LoginServiceImpl.class);
    private static final String charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=";
    private static final Integer INACTIVE = 0;
    private static final Integer ACTIVE = 1;

    
    @Override
    public int performLogin(String username, String password) throws Exception{

		int output = 1; // valid password
		UserDetails userDetails =getServiceDAO().getUserDetails(username,password);

		if (userDetails != null && userDetails.getStatus() == 2) {
			output = 3; // Account locked
		}
		else if (userDetails != null
				&& userDetails.getPassword()!=null) {
			// valid password
			if (userDetails != null && userDetails.getCreationDate()== null) {

				output = 4; // first logon
			}
	
		}
		else {
			output = 2; // Invalid password
		}

		return output;
	}

    @Override
    public LoginDao getServiceDAO() {
	return (LoginDao) getBaseDAO();
    }

    public UserDetails chkValidUser(String emailId) {
	UserDetails userDetails; 
	userDetails = getServiceDAO().getUserDetails(emailId);
	return userDetails;
    }

    @Override
    public int getUserInfo(String emailId) {
	return getServiceDAO().getUserInfo(emailId).getEmployeeId();
    }

	@Override
	public UserLog loadUserInfo(String emailId) {
		UserLog userInfo = null;
		UserDetails userDetails = null;
		userDetails = getServiceDAO().getUserDetails(emailId);
		if (userDetails != null) {
			getServiceDAO().getUserInfo(emailId);
			userInfo = new UserLog();
			userInfo.setUserDetails(userDetails);
			java.util.Date date = new java.util.Date();
			userInfo.setLoginTime(new Timestamp(date.getTime()));
		}
		return userInfo;
	}

	@Override
	public String txUpdateUserDetails(String emaild, int flag) {
		String password = "";
		UserDetails userDetails;
		userDetails = /*
					 * (UserDetails) getServiceDAO().findById(
					 * UserDetails.class,
					 */
		getServiceDAO().getUserDetails(emaild);// .getSlNo());
		switch (flag) {
		case 4: // update Lastaccessed date

			try {
				java.util.Date date = new java.util.Date();
				//userDetails.setLastAccess(new Timestamp(date.getTime()));
			} catch (Exception e) {
				LOG.error("Exception in txUpdateUserDetails:", e);
			}

			break;
		case 5:// lock account
			if (userDetails != null) {
				userDetails.setStatus(INACTIVE);
			}
			break;

		case 6:// Reset password

			try {
				password = getRandomString();
				//userDetails.setLastAccess(null);
			} catch (Exception e) {
				LOG.error("", e);
			}
			userDetails.setStatus(ACTIVE);
		default:
		}
		getServiceDAO().updateObject(userDetails);
		return password;

	}

        
    public String getRandomString(int length) {
        Random rand = new Random(System.currentTimeMillis());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int pos = rand.nextInt(charset.length());
            sb.append(charset.charAt(pos));
        }
        return sb.toString();
    }

    public String getRandomString(){
	return getRandomString(10);
    }
    
    public String getEmpRoles(int empSlNo)
    {
      String strRoleId = "";
      List<Role> empRoles = getServiceDAO().getEmpRole(empSlNo);
      for(Role rp: empRoles)
      {
          strRoleId = strRoleId + "," + rp.getRoleId();
      }
      return strRoleId;
    }

    
    public void txResetAcctLockStatus(String emaild){
    	UserDetails userDetails; 
    	userDetails = getServiceDAO().getUserDetails(emaild);//.getSlNo());
    	    if(userDetails != null){
	    		userDetails.setStatus(ACTIVE);
	   	    	getServiceDAO().updateObject(userDetails);
    	    }
    }

}
